package cn.edu.nuc.android.oweibo.authorization;

import java.io.InputStream;
import java.util.Properties;

import weibo4android.Weibo;
import weibo4android.http.AccessToken;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import cn.edu.nuc.android.oweibo.R;

public class OAuthHelper {
	
	private static final String AUTH_KEY = "auth_key";
	private static final String AUTH_SECRET_KEY = "auth_secret_key";
	private static final String APPLICATION_PREFERENCES = "app_prefs";
	private SharedPreferences prefs;
	private Context context;
	private String consumerSecretKey;
	private String consumerKey;
	private AccessToken accessToken;

	public OAuthHelper(Context context) {
		super();
		this.context = context;
		
		// File creation mode: the default mode, where the created file can only
		// be accessed by the calling application (or all applications sharing
		// the same user ID).
		prefs = context.getSharedPreferences(APPLICATION_PREFERENCES, Context.MODE_PRIVATE);
		loadConsumerKeys();
		accessToken = loadAccessToken();
	}

	public boolean hasAccessToken() {
		return null != accessToken;
	}

	/**
	 * ����OAuth��consumer_key and consumer_secret_key��
	 * @param weibo
	 */
	public void configureOAuth(Weibo weibo) {
		weibo.setOAuthConsumer(consumerKey, consumerSecretKey);
		weibo.setOAuthAccessToken(accessToken);
	}

	/**
	 * �洢AccessToken
	 * @param accessToken
	 */
	public void storeAccessToken(AccessToken accessToken) {
		Editor editor = prefs.edit();
		editor.putString(AUTH_KEY, accessToken.getToken());
		editor.putString(AUTH_SECRET_KEY, accessToken.getTokenSecret());
		editor.commit();
		this.accessToken = accessToken;
	}
	
	/**
	 * ����AccessToken
	 * @return
	 */
	private AccessToken loadAccessToken() {
		String token = prefs.getString(AUTH_KEY, null);
		String tokenSecret = prefs.getString(AUTH_SECRET_KEY, null);
		if (null != token && null != tokenSecret) {
			return new AccessToken(token, tokenSecret);
		} else {
			return null;
		}
	}


	/**
	 * �����û���Կ
	 */
	private void loadConsumerKeys() {
		try {
			Properties props = new Properties();
			InputStream inputStream = context.getResources().openRawResource(R.raw.oauth);
			props.load(inputStream);
			consumerKey = (String)props.getProperty("consumer_key");
			consumerSecretKey = (String)props.getProperty("consumer_secret_key");
		} catch (Exception e) {
			throw new RuntimeException("Unable to load consumer keys from oauth.properties", e);
		}
	}
}
